<?php
namespace app\common\job;

use app\common\model\RoymqQueueModel;
use think\facade\Log;
use think\queue\Job;

class QueueJob
{
    /**
     * 创建队列
     * @author 贺强
     * @time   2022/6/27 17:00
     * @param Job   $job  当前任务
     * @param array $data 创建参数
     * @return bool
     */
    public function add_queue(Job $job, array $data = []) : bool
    {
        if (empty($data['QueueName'])) {
            $job->delete();
            return false;
        }
        try {
            $data_new = [];
            foreach ($data as $k => $v) {
                $data_new[unhump($k)] = $v;
            }
            $res = RoymqQueueModel::add($data_new);
            if ($res) {
                $job->delete();
                return true;
            } elseif ($job->attempts() > 10) {
                $job->delete();
                $error = ['jobName' => $job->getName(), 'data' => $data];
                throw new \Exception('执行次数超限:' . json_encode($error));
            } else {
                $job->release(3);
                return false;
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            $job->delete();
            return false;
        }
    }
}
